package com.xlh.controller.statistic;

import cn.hutool.core.util.ObjectUtil;
import com.xlh.aop.statistic.StatisticPreAcquireLock;
import com.xlh.common.Result;
import com.xlh.dto.PageDTO;
import com.xlh.dto.statistic.*;
import com.xlh.param.statistic.UserInfoParam;
import com.xlh.security.SpringSecurityUserInfoHolder;
import com.xlh.service.statistic.StatisticService;
import com.xlh.support.attendance.po.SettingMarkPO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;

import static com.xlh.constant.StatisticConstant.STATISTIC;

/**
 * 统计
 * <p>
 * Created by lx on 2020/9/25.
 */
@Api(tags = "StatisticController", description = "课程班级统计")
@RestController
@RequestMapping("/statistic")
public class StatisticController {

    @Autowired
    private StatisticService statisticService;

    @ApiOperation("查询班级的手动更新时间")
    @GetMapping("/class/{classId}/update-time")
    @PreAuthorize("@permissionValidator.isTeacher()")
    @StatisticPreAcquireLock(value = STATISTIC, type = 2)
    public Result<String> queryCourseClassUpdateTime(@PathVariable("classId") Long classId) {
        return Result.success(statisticService.getClassUpdateTime(classId));
    }

    @ApiOperation("针对于班级手动更新")
    @PostMapping("/class/{classId}")
    @PreAuthorize("@permissionValidator.isTeacher()")
    @StatisticPreAcquireLock(value = STATISTIC)
    public Result noAutoUpdate(@PathVariable("classId") Long classId,
                               @Autowired SpringSecurityUserInfoHolder userInfoHolder) {
        statisticService.noAutoUpdate(userInfoHolder.getUserId(), classId);
        return Result.success();
    }

    // ---------------- 教学统计  ----------------

    @ApiOperation("针对于课程班级下载")
    @PostMapping("/course/{courseId}/class/{classId}/download")
    @PreAuthorize("@permissionValidator.isTeacher()")
    @StatisticPreAcquireLock(value = STATISTIC, type = 2)
    public Result downloadCourseClass(@PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId) {
        statisticService.downloadCourseClass(courseId, classId);
        return Result.success();
    }

    @ApiOperation("查询课程班级的整体统计")
    @GetMapping("/course/{courseId}/class/{classId}")
    @PreAuthorize("@permissionValidator.isTeacher()")
//    @StatisticPreAcquireLock(value = STATISTIC, type = 2)
    public Result<StatisticDTO> queryCourseClassStatistic(
            @PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId) {
        return Result.success(statisticService.queryCourseClassStatistic(courseId, classId));
    }

    @ApiOperation("查询课程班级的随堂练习统计（出错率）")
    @GetMapping("/course/{courseId}/class/{classId}/practice")
    @PreAuthorize("@permissionValidator.isTeacher()")
//    @StatisticPreAcquireLock(value = STATISTIC, type = 2)
    public Result<List<StudentChapterDTO>> queryPracticeStatistic(
            @PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId,
            @RequestParam(required = false, defaultValue = "50") Integer errorRate) {
        return Result.success(statisticService.queryPracticeStatistic(courseId, classId, errorRate));
    }

    @ApiOperation("查询课程班级的考试统计")
    @GetMapping("/course/{courseId}/class/{classId}/exam/{examId}")
    @PreAuthorize("@permissionValidator.isTeacher()")
//    @StatisticPreAcquireLock(value = STATISTIC, type = 2)
    public Result<StudentExamDTO> queryCourseClassExam(
            @PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId,
            @PathVariable("examId") Long examId) {
        return Result.success(statisticService.queryCourseClassExam(courseId, classId, examId));
    }

    // ---------------- 考勤、时长、随堂提问、问题交流详情  ----------------
    // 新增type区分来源 无type则表示
    @ApiOperation("查询课程班级的统计详情（考勤、时长、随堂提问、问题交流详情）")
    @PostMapping({"/course/{courseId}/class/{classId}/detail"})
    @PreAuthorize("@permissionValidator.isTeacher()")
    public Result<List<StatisticInfoDTO>> listStudentCourse(
            @PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId,
            @RequestBody @Valid UserInfoParam param) {
        if(ObjectUtil.isNotNull(param.isUpdateType())){
            if(param.isUpdateType()){
                statisticService.updateStatistic(classId);
            }
        }
        return Result.success(statisticService.queryStudentCourse(courseId, classId, param));
    }


    @ApiOperation("满分项设置")
    @PostMapping("/course/{courseId}/class/{classId}/settingfullmark")
    @PreAuthorize("@permissionValidator.isTeacher()")
    public Result settingfullmark(@RequestBody @Valid SettingMarkPO settingMarkPO) {
        statisticService.settingFullMark(settingMarkPO);
        return Result.success();
    }

    @ApiOperation("满分项获取")
    @GetMapping("/course/{courseId}/class/{classId}/getfullmark")
    @PreAuthorize("@permissionValidator.isTeacher()")
    public Result getfullmark(
            @PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId) {
        Integer fullMark = statisticService.getfullmark(courseId, classId);
        return Result.success(fullMark);
    }


    @ApiOperation("分数设置")
    @GetMapping("/course/{courseId}/class/{classId}/settingscore")
    @PreAuthorize("@permissionValidator.isTeacher()")
    public Result settingScore(@RequestParam("id") Long id, @RequestParam("score")Integer score) {
        statisticService.settingScore(id, score);
        return Result.success();
    }

    @ApiOperation("数据导出")
    @PostMapping("/course/{courseId}/class/{classId}/exportdata")
    @PreAuthorize("@permissionValidator.isTeacher()")
    public Result<List<StatisticInfoDTO>> exportData(
            @PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId,
            @RequestBody @Valid UserInfoParam param,
            HttpServletRequest request,
            HttpServletResponse response ) {
        statisticService.exportData(courseId, classId, param, request, response);
        return null;
    }


    // ---------------- 考试详情  ----------------

    @ApiOperation("查询课程班级的考试统计详情")
    @PostMapping("/course/{courseId}/class/{classId}/exam/{examId}/detail")
    @PreAuthorize("@permissionValidator.isTeacher()")
//    @StatisticPreAcquireLock(value = STATISTIC, type = 2)
    public Result<ExamDTO> listTruant(
            @PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId,
            @PathVariable("examId") Long examId, @RequestBody @Valid UserInfoParam param) {
        return Result.success(statisticService.queryExamList(courseId, classId, examId, param));
    }

    // ---------------- 随堂练习、实验报告、实验判定详情  ----------------

    @ApiOperation("查询课程班级的任务详情（实验报告、实验通过）")
    @PostMapping("/course/{courseId}/class/{classId}/task")
    @PreAuthorize("@permissionValidator.isTeacher()")
//    @StatisticPreAcquireLock(value = STATISTIC, type = 2)
    public Result<List<TaskDTO>> listTask(
            @PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId,
            @RequestBody @Valid UserInfoParam param) {
        return Result.success(statisticService.queryTaskList(courseId, classId, param));
    }

    @ApiOperation("查询课程班级的任务信息分页（实验报告、实验通过）")
    @GetMapping("/course/{courseId}/class/{classId}/task/{userId}")
    @PreAuthorize("@permissionValidator.isTeacher()")
//    @StatisticPreAcquireLock(value = STATISTIC, type = 2)
    public Result<PageDTO<StudentTaskDTO>> listTaskPage(
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer type,
            @PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId,
            @PathVariable("userId") Long userId) {
        return Result.success(statisticService.queryStudentTaskByPage(pageNum, pageSize,
                courseId, classId, userId, type));
    }

    @ApiOperation("查询当前学生的课程班级的任务信息分页（实验报告、实验通过）")
    @GetMapping("/course/{courseId}/class/{classId}/task")
    @PreAuthorize("@permissionValidator.isStudent()")
    public Result<PageDTO<StudentTaskDTO>> listStudentTaskPage(
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer type,
            @PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId,
            @Autowired SpringSecurityUserInfoHolder userInfoHolder) {
        return Result.success(statisticService.queryStudentTaskByPage(pageNum, pageSize,
                courseId, classId, userInfoHolder.getUserId(), type));
    }

    @ApiOperation("课程班级的任务下载（实验报告、实验通过）")
    @PostMapping("/course/{courseId}/class/{classId}/task/download")
    @PreAuthorize("@permissionValidator.isTeacher()")
    @StatisticPreAcquireLock(value = STATISTIC, type = 2)
    public Result downloadTask(
            @PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId,
            @RequestBody @Valid UserInfoParam param) {
        statisticService.downloadTask(courseId, classId, param);
        return Result.success();
    }

    @ApiOperation("查询课程班级的章节详情（随堂练习）")
    @PostMapping("/course/{courseId}/class/{classId}/chapter")
    @PreAuthorize("@permissionValidator.isTeacher()")
    @StatisticPreAcquireLock(value = STATISTIC, type = 2)
    public Result<List<ChapterDTO>> listChapter(
            @PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId,
            @RequestBody @Valid UserInfoParam param) {
        return Result.success(statisticService.queryChapterList(courseId, classId, param));
    }

    @ApiOperation("查询课程班级的章节信息分页（随堂练习）")
    @GetMapping("/course/{courseId}/class/{classId}/chapter/{userId}")
    @PreAuthorize("@permissionValidator.isTeacher()")
//    @StatisticPreAcquireLock(value = STATISTIC, type = 2)
    public Result<PageDTO<StudentChapterDTO>> listChapterPage(
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId,
            @PathVariable("userId") Long userId) {
        return Result.success(statisticService.queryStudentChapterByPage(pageNum, pageSize, courseId, classId, userId));
    }

    @ApiOperation("查询当前学生的课程班级的章节信息分页（随堂练习）")
    @GetMapping("/course/{courseId}/class/{classId}/chapter")
    @PreAuthorize("@permissionValidator.isStudent()")
//    @StatisticPreAcquireLock(value = STATISTIC, type = 2)
    public Result<PageDTO<StudentChapterDTO>> listStudentChapterPage(
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId,
            @Autowired SpringSecurityUserInfoHolder userInfoHolder) {
        return Result.success(statisticService.queryStudentChapterByPage(pageNum, pageSize,
                courseId, classId, userInfoHolder.getUserId()));
    }

    @ApiOperation("课程班级的章节下载（随堂练习）")
    @PostMapping("/course/{courseId}/class/{classId}/chapter/download")
    @PreAuthorize("@permissionValidator.isTeacher()")
    @StatisticPreAcquireLock(value = STATISTIC, type = 2)
    public Result downloadChapter(
            @PathVariable("courseId") Long courseId, @PathVariable("classId") Long classId,
            @RequestBody @Valid UserInfoParam param) {
        statisticService.downloadChapter(courseId, classId, param);
        return Result.success();
    }

}
